package com.sfzd5.exam;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.sfzd5.exam.helplibrary.exam.ExamInof;
import com.sfzd5.exam.helplibrary.exam.QRCodeModel;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import cn.bingoogolapple.qrcode.core.BarcodeType;
import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zbar.ZBarView;

public class QRCodeActivity extends AppCompatActivity implements QRCodeView.Delegate {

    private static final String TAG = QRCodeActivity.class.getSimpleName();

    private ZBarView mZBarView;
    PApplication app;
    Handler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qrcode);

        app = (PApplication) getApplication();
        app.wsClient.wsMessageListener = new WSMessageListener() {
            @Override
            public void onWSMessage(String msg) {

            }
        };

        handler = new Handler();

        mZBarView = findViewById(R.id.zbarview);
        mZBarView.setDelegate(this);

        mZBarView.changeToScanQRCodeStyle(); // 切换成扫描二维码样式
        mZBarView.setType(BarcodeType.ONLY_QR_CODE, null); // 只识别 QR_CODE
        //mZBarView.startSpotAndShowRect(); // 显示扫描框，并开始识别

        mZBarView.showScanRect(); // 显示扫描框
        mZBarView.getScanBoxView().setOnlyDecodeScanBoxArea(true); // 仅识别扫描框中的码

        //mZBarView.startCamera(); // 打开后置摄像头开始预览，但是并未开始识别
        mZBarView.startSpot(); // 开始识别
    }

    @Override
    protected void onStart() {
        super.onStart();
        mZBarView.startCamera(); // 打开后置摄像头开始预览，但是并未开始识别
//      mZBarView.startCamera(Camera.CameraInfo.CAMERA_FACING_FRONT); // 打开前置摄像头开始预览，但是并未开始识别
        mZBarView.startSpotAndShowRect(); // 显示扫描框，并开始识别
    }

    @Override
    protected void onStop() {
        mZBarView.stopCamera(); // 关闭摄像头预览，并且隐藏扫描框
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        mZBarView.onDestroy(); // 销毁二维码扫描控件
        super.onDestroy();
    }

    /**
     * 振动
     */
    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }

    @Override
    public void onScanQRCodeSuccess(String result) {
        Log.i(TAG, "result:" + result);
        //setTitle("扫描结果为：" + result);
        //振动
        vibrate();

        mZBarView.stopSpot(); // 停止识别
        //mZBarView.stopCamera(); // 关闭摄像头预览，并且隐藏扫描框
        //mZBarView.startSpot(); // 开始识别

        QRCodeModel qrCodeModel = new Gson().fromJson(result, QRCodeModel.class);
        new downTask().execute(qrCodeModel.taskId);

        //下载
        Toast.makeText(QRCodeActivity.this, "识别成功，正在下载试题信息", Toast.LENGTH_LONG).show();
    }

    void delayFinish(int delay){
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                QRCodeActivity.this.finish();
            }
        }, delay);
    }

    class downTask extends AsyncTask<Long, Integer, Integer>{
        static final int hasSubmit = -1;
        static final int startCamera = 1;
        static final int fail = 0;

        @Override
        protected void onPostExecute(Integer integer) {
            super.onPostExecute(integer);
            if(integer == hasSubmit){
                delayFinish(3000);
                Toast.makeText(QRCodeActivity.this, "该作业已经提交", Toast.LENGTH_LONG).show();
            } else if(integer == startCamera){
                //数据已经设置好了，可以开始扫描了
                QRCodeActivity.this.startActivity(new Intent(QRCodeActivity.this, CameraActivity.class));
            } else {
                delayFinish(3000);
                Toast.makeText(QRCodeActivity.this, "获取数据失败", Toast.LENGTH_LONG).show();
            }
        }

        @Override
        protected Integer doInBackground(Long... integers) {
            long taskId = integers[0];
            PApplication app = (PApplication) getApplication();
            try {
                InputStream is = getResources().openRawResource(R.raw.examinfo);
                InputStreamReader isr = new InputStreamReader(is,"UTF-8");
                BufferedReader br = new BufferedReader(isr);
                String str = "";
                StringBuffer sb = new StringBuffer();
                while((str = br.readLine()) != null){
                    sb.append(str+"\n");
                }
                ExamInof examInof = new Gson().fromJson(sb.toString(), ExamInof.class);
                app.setNewExamInfo(examInof);
                return startCamera;

            } catch (IOException e) {
                e.printStackTrace();
            }

            return fail;
        }
    }

    @Override
    public void onCameraAmbientBrightnessChanged(boolean isDark) {
        // 这里是通过修改提示文案来展示环境是否过暗的状态，接入方也可以根据 isDark 的值来实现其他交互效果
        String tipText = mZBarView.getScanBoxView().getTipText();
        String ambientBrightnessTip = "\n环境过暗，请打开闪光灯";
        if (isDark) {
            if (!tipText.contains(ambientBrightnessTip)) {
                mZBarView.getScanBoxView().setTipText(tipText + ambientBrightnessTip);
            }
        } else {
            if (tipText.contains(ambientBrightnessTip)) {
                tipText = tipText.substring(0, tipText.indexOf(ambientBrightnessTip));
                mZBarView.getScanBoxView().setTipText(tipText);
            }
        }
    }

    @Override
    public void onScanQRCodeOpenCameraError() {
        Log.e(TAG, "打开相机出错");
        Toast.makeText(QRCodeActivity.this, "打开相机出错", Toast.LENGTH_LONG).show();
    }
}
